/* --
 * Chris Baird/VK2CJB <cjb@brushtail.apana.org.au>
 */

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

#define CHANNEL (81) // something the local WiFi doesn't spam

RF24 radio (9, 10); // CE, CSN - Nano/Uno wiring

const uint8_t* address = "MOMO";

#define PACKETSIZE (26)
uint8_t payload[PACKETSIZE];

// ----------------------------------------------------------------------

void setup (void)
{
  Serial.begin (115200);
  while (!Serial) continue;

  while (!radio.begin()) delay (10);

  radio.setChannel (CHANNEL);
  radio.setPayloadSize (PACKETSIZE);
  //radio.setRetries (5, 15);
  radio.setDataRate (RF24_250KBPS);
  radio.setPALevel (RF24_PA_LOW, 1);
  radio.setCRCLength (RF24_CRC_16);
  radio.setAutoAck (true);
  radio.setAddressWidth (4);
  radio.openWritingPipe (address);
  radio.openReadingPipe (1, address);
  radio.txDelay = 75;		/* 75 */
  radio.startListening();
}

// ----------------------------------------------------------------------

void check_rx (void)
{
  if (radio.available())
    {
      int visible = 1;
      radio.read (payload, PACKETSIZE);
      Serial.write (':');
      for (int i = 0; i < PACKETSIZE; i++)
	{
	  if (payload[i] < 16) Serial.write (48);
	  Serial.print (payload[i], HEX);
	  if ((payload[i] < 32) || (payload[i] > 126))
	    visible = 0;
	}
      Serial.println();

      // if packet was only 'visible' characters, output as a string.
      if (visible)
	{
	  for (int i = 0; i < PACKETSIZE; i++)
	    Serial.write ((char)payload[i]);
	  Serial.println();
	}
    }
}

// ----------------------------------------------------------------------

void check_serial (void)
{
  if (Serial.available())
    {
      char cmd = 0, time = 0;
      cmd = Serial.read();
      if ((cmd < 'A' || cmd > 'Z') && (cmd < 'a' || cmd > 'z'))
	return;

      while (Serial.available() < 1) continue;
      time = Serial.read();
      if (time < '0' || time > '9')
	return;

      time -= 48;

      payload[0] = cmd;
      payload[1] = time;
      radio.stopListening();
      radio.write (payload, 32);
      radio.startListening();
    }
}

// ----------------------------------------------------------------------

void loop (void)
{
  check_serial();
  check_rx();
}

// ----------------------------------------------------------------------
